package com.ruoyi.feike.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.AnnualReviewy;
import com.ruoyi.feike.domain.Fileupload;
import com.ruoyi.feike.domain.ParkingLocation;
import com.ruoyi.feike.domain.ParkingLocationRegistration;
import com.ruoyi.feike.domain.vo.AnnualReviewyHistoryVO;
import com.ruoyi.feike.mapper.AnnualReviewyMapper;
import com.ruoyi.feike.mapper.ParkingLocationMapper;
import com.ruoyi.feike.mapper.ParkingLocationRegistrationMapper;
import com.ruoyi.feike.service.IFileuploadService;
import com.ruoyi.feike.service.IParkingLocationRegistrationService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * feikeService业务层处理
 * 
 * @author ruoyi
 * @date 2022-08-02
 */
@Service
public class ParkingLocationRegistrationServiceImpl implements IParkingLocationRegistrationService 
{
    @Autowired
    private ParkingLocationRegistrationMapper parkingLocationRegistrationMapper;

    @Autowired
    private ParkingLocationMapper parkingLocationMapper;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    @Autowired
    private IFileuploadService fileuploadService;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    /**
     * 查询feike
     * 
     * @param id feikeID
     * @return feike
     */
    @Override
    public Map<String, Object> selectParkingLocationRegistrationById(String id)
    {
        Map<String, Object> map=new HashMap<>();
        List<ParkingLocationRegistration> list=new ArrayList();

        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyById(id);
        List<ParkingLocationRegistration> parkingLocationRegistrationList = parkingLocationRegistrationMapper.selectParkingLocationRegistrationByInstancsId(annualReviewy.getInstanceId());
        System.out.println("parkingLocationRegistrationList=="+parkingLocationRegistrationList);
        if (parkingLocationRegistrationList!=null&&parkingLocationRegistrationList.size()>0){
            for (ParkingLocationRegistration parkingLocationRegistration : parkingLocationRegistrationList) {
                System.out.println("parkingLocationRegistration对象=="+parkingLocationRegistration);
                // String parkinglocation = parkingLocation.getProvince();
                String parkinglocation1 = parkingLocationRegistration.getParkinglocation();
                if(!StringUtils.isEmpty(parkinglocation1)){
                    boolean contains = parkinglocation1.contains(",");
                    if (contains){
                        String[] split = parkinglocation1.split(",");
                        System.out.println("split=="+split.toString());
                        parkingLocationRegistration.setParkinglocations(split);
                    }
                }

                String vin = parkingLocationRegistration.getVin();
                if(!StringUtils.isEmpty(vin)){
                    boolean contains = parkinglocation1.contains(",");
                    if (contains){
                        String[] vins = vin.split(",");
                        parkingLocationRegistration.setVins(vins);
                    }
                }

                List<Fileupload> fileuploadList=fileuploadService.selectFileuploadByInstanceId(parkingLocationRegistration.getId());
                System.out.println("fileuploadList=="+fileuploadList);
                parkingLocationRegistration.setUploadFile(fileuploadList);
                String dealernamecn = parkingLocationRegistration.getDealerName();
                String groupName = parkingLocationRegistration.getGroupNameCn();

                map.put("groupName",groupName);
                map.put("dealerName",dealernamecn);
                list.add(parkingLocationRegistration);
            }
        }

        map.put("id",annualReviewy.getId());
        map.put("instanceId",annualReviewy.getInstanceId());
        map.put("data",list);
        System.out.println("返回的map数据=="+map);
        return map;
    }

    @Override
    public Map<String, Object> selectParkingLocationRegistrationByInstanceId(String instanceId) {
        Map<String, Object> map=new HashMap<>();
        List<ParkingLocationRegistration> list=new ArrayList();
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
        List<ParkingLocationRegistration> parkingLocationRegistrationList = parkingLocationRegistrationMapper.selectParkingLocationRegistrationByInstancsId(annualReviewy.getInstanceId());
        System.out.println("parkingLocationRegistrationList=="+parkingLocationRegistrationList);
        if (parkingLocationRegistrationList!=null&&parkingLocationRegistrationList.size()>0){
            for (ParkingLocationRegistration parkingLocationRegistration : parkingLocationRegistrationList) {
                System.out.println("parkingLocationRegistration对象=="+parkingLocationRegistration);
                String parkinglocation1 = parkingLocationRegistration.getParkinglocation();
                String[] split = parkinglocation1.split(",");
                System.out.println("split=="+split.toString());
                parkingLocationRegistration.setParkinglocations(split);
                String vin = parkingLocationRegistration.getVin();
                String[] vins = vin.split(",");
                parkingLocationRegistration.setVins(vins);

                List<Fileupload> fileuploadList=fileuploadService.selectFileuploadByInstanceId(parkingLocationRegistration.getId());
                System.out.println("fileuploadList=="+fileuploadList);
                parkingLocationRegistration.setUploadFile(fileuploadList);
                String dealernamecn = parkingLocationRegistration.getDealerName();
                String groupName = parkingLocationRegistration.getGroupNameCn();

                map.put("groupName",groupName);
                map.put("dealerName",dealernamecn);
                list.add(parkingLocationRegistration);
            }
        }

        map.put("id",annualReviewy.getId());
        map.put("instanceId",annualReviewy.getInstanceId());
        map.put("data",list);
        System.out.println("返回的map数据=="+map);
        return map;

    }

    /**
     * 查询feike列表
     * 
     * @param parkingLocationRegistration feike
     * @return feike
     */
    @Override
    public List<ParkingLocationRegistration> selectParkingLocationRegistrationList(ParkingLocationRegistration parkingLocationRegistration)
    {
        return parkingLocationRegistrationMapper.selectParkingLocationRegistrationList(parkingLocationRegistration);
    }

    /**
     * 新增feike
     * 
     * @param parkingLocationRegistration feike
     * @return 结果
     */
    @Override
    public int insertParkingLocationRegistration(ParkingLocationRegistration parkingLocationRegistration)
    {
        System.out.println("parkingLocationRegistration新增对象： "+parkingLocationRegistration);
        String instanceId = IdUtils.simpleUUID();
        String id = instanceId;
        String title = SecurityUtils.getLoginUser().getUser().getNickName()+"-"+"Parking locationregistration流程";
        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                                                           .getUser()
                                                           .getUserId()
                                                           .toString());
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("parkingLocationregistration")
                .withName(title)
                .withBusinessKey(instanceId)
                // .withVariable("deptLeader",join)
                .build());

        Task task = null;
        task = taskService.createTaskQuery()
                          .processInstanceId(processInstance.getId())
                          .singleResult();
        TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
        List<Task> todoList = query.list();//获取申请人的待办任务列表
        for (Task tmp : todoList) {
            if(tmp.getProcessInstanceId().equals(processInstance.getId())){
                task = tmp;//获取当前流程实例，当前申请人的待办任务
                break;
            }
        }
        HashMap<String, Object> variables = new HashMap<String, Object>();
        // List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
        // for (Map<String, Object> form : actForm) {
        //     variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
        // }
        variables.put("toUnderwriter", 0);
        taskService.complete(task.getId(), variables);

        parkingLocationRegistration.setId(id);
        parkingLocationRegistration.setInstanceId(id);

        ParkingLocation parkingLocation=new ParkingLocation();


        AnnualReviewy annualReviewy=new AnnualReviewy();
        annualReviewy.setId(id);
        annualReviewy.setInstanceId(processInstance.getId());
        annualReviewy.setTitle(title);
        annualReviewy.setType(parkingLocationRegistration.getType());  // TODO 待确认，先暂时随便写一个
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setState("0");
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        // annualReviewy.setUsername(); // TODO 先不填

        int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);
        if (i==0){
            return 0;
        }else {
            return parkingLocationRegistrationMapper.insertParkingLocationRegistration(parkingLocationRegistration);
            // ParkingLocation parkingLocation=new ParkingLocation();
            // BeanUtils.copyProperties(parkingLocationRegistration,parkingLocation);
            // return parkingLocationMapper.insertParkingLocation(parkingLocation);
        }
    }

    /**
     * 修改feike
     * 
     * @param parkingLocationRegistration feike
     * @return 结果
     */
    @Override
    public int updateParkingLocationRegistration(ParkingLocationRegistration parkingLocationRegistration)
    {
        System.out.println("parkingLocationRegistration修改对象： "+parkingLocationRegistration);
        return parkingLocationRegistrationMapper.updateParkingLocationRegistration(parkingLocationRegistration);
    }

    /**
     * 批量删除feike
     * 
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteParkingLocationRegistrationByIds(String[] ids)
    {
        System.out.println("parkingLocationRegistration删除对象： "+ids);
        List<AnnualReviewy> annualReviewyList = annualReviewyMapper.selectAnnualReviewyByIds(ids);
        int num=0;
        if (annualReviewyList != null && annualReviewyList.size() > 0) {
            for (AnnualReviewy annualReviewy : annualReviewyList) {
                int i = parkingLocationRegistrationMapper.deleteParkingLocationRegistrationById(annualReviewy.getId());
                if (i==0){
                    return 0;
                }else {
                    num=num+1;
                    return annualReviewyMapper.deleteAnnualReviewyById(annualReviewy.getId());
                }

            }
        }
       return num;
    }

    /**
     * 删除feike信息
     * 
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteParkingLocationRegistrationById(String id)
    {
        return parkingLocationRegistrationMapper.deleteParkingLocationRegistrationById(id);
    }

    @Override
    public List<AnnualReviewyHistoryVO> selectParkingLocationRegistrationListAll(AnnualReviewy annualReviewy, ParkingLocationRegistration parkingLocationRegistration) {
        return parkingLocationRegistrationMapper.selectParkingLocationRegistrationListBySelf(annualReviewy, parkingLocationRegistration, SecurityUtils.getLoginUser()
                                                                                                               .getUser()
                                                                                                               .getDeptId());
    }

    /**
     * 根据group和dealer获取详细信息
     */
    @Override
    public Map<String, Object> selectParkingLocationRegistration(Map<String, Object> map) {
        System.out.println("ParkingLocationRegistration查询： "+map);
        List<Map<String, Object>> dealerList = (List<Map<String, Object>>) map.get("dealerList");
        Map<String, Object> parkingLocationMap=new HashMap<>();
        List<ParkingLocation> list=new ArrayList<>();

        if (dealerList!=null&&dealerList.size()>0){
            for (Map<String, Object> dealerObj : dealerList) {
                // 获取groupId 和 dealerId信息
                String groupName = (String) dealerObj.get("groupName");
                String dealerName = (String) dealerObj.get("dealerName");
                // 根据groupId和dealerId获取详细信息
                ParkingLocation parkingLocation=parkingLocationRegistrationMapper.selectParkingLocationRegistrationByGroupNameAndDealerName(groupName,dealerName);
                list.add(parkingLocation);
            }
        }
        if (list!=null&&list.size()>0){
            parkingLocationMap.put("dealerList",list);
        }
        System.out.println("parkingLocationMap=="+parkingLocationMap);
        return parkingLocationMap;
    }

    @Override
    public int insertParkingLocationRegistrationMap(Map<String, Object> map) {
        System.out.println("=======1111===="+map);
        String instanceId = IdUtils.simpleUUID();
        // String id = instanceId;
        // String id = (String) map.get("id");
        String title = SecurityUtils.getLoginUser().getUser().getNickName()+"-"+"Parking locationregistration流程";
        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                                                           .getUser()
                                                           .getUserId()
                                                           .toString());
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("parkingLocationregistration")
                .withName(title)
                .withBusinessKey(instanceId)
                // .withVariable("deptLeader",join)
                .build());

        Task task = null;
        task = taskService.createTaskQuery()
                          .processInstanceId(processInstance.getId())
                          .singleResult();
        TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
        List<Task> todoList = query.list();//获取申请人的待办任务列表
        for (Task tmp : todoList) {
            if(tmp.getProcessInstanceId().equals(processInstance.getId())){
                task = tmp;//获取当前流程实例，当前申请人的待办任务
                break;
            }
        }
        HashMap<String, Object> variables = new HashMap<String, Object>();

        variables.put("toUnderwriter", 0);
        taskService.complete(task.getId(), variables);

        // 下面业务数据
        String groupName = map.get("groupName")!=null?(String) map.get("groupName"):"";
        String dealerName = map.get("dealerName")!=null?(String) map.get("dealerName"):"";
        Object form = map.get("form");
        if (form!=null){
            List<Map<String,Object>> list = (List<Map<String, Object>>) form;
            if (list!=null&&list.size()>0){
                for (Map<String, Object> obj : list) {
                    ParkingLocationRegistration parkingLocationRegistration = new ParkingLocationRegistration();

                    parkingLocationRegistration.setInstanceId(instanceId);
                    if(!StringUtils.isEmpty(groupName)){
                        parkingLocationRegistration.setGroupNameCn(groupName);
                    }
                    if(!StringUtils.isEmpty(dealerName)){
                        parkingLocationRegistration.setDealerName(dealerName);
                    }

                    String provinceCN = (String) obj.get("provinceCN"); //存中文地址
                    if (!StringUtils.isEmpty(provinceCN)){
                        parkingLocationRegistration.setProvinceCN(provinceCN);
                    }
                    StringBuilder province = new StringBuilder();
                    Object province1 = obj.get("province");     // 存数组转的字符串  省市县
                    if(province1!=null && !StringUtils.isEmpty(String.valueOf(province1))){
                        List provinceList = (List) province1;// 前端传的是数组
                        if (provinceList!=null&&provinceList.size()>0){
                            String provinceName = (String) provinceList.get(0);
                            String city = (String) provinceList.get(1);
                            String county = (String) provinceList.get(2);
                            parkingLocationRegistration.setProvince(provinceName);   // 省
                            parkingLocationRegistration.setCity(city);       // 市
                            parkingLocationRegistration.setCounty(county);     // 县
                            for (int i = 0; i < provinceList.size(); i++) {
                                province.append(provinceList.get(i));
                                province.append(",");
                            }
                        }
                    }
                    if (!StringUtils.isEmpty(province)){
                        province.deleteCharAt(province.length()-1);
                        parkingLocationRegistration.setParkinglocation(province.toString());
                        System.out.println("province"+province);
                    }

                    Object type = obj.get("type");
                    if (type!=null){
                        parkingLocationRegistration.setType((String) type);
                    }

                    String startDate = (String) obj.get("startDate");
                    String endDate = (String) obj.get("endDate");
                    SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
                    Date startTime = new Date();
                    Date endTime = new Date();
                    try {
                        if (!StringUtils.isEmpty(startDate)){
                            startTime = format.parse(startDate);
                            parkingLocationRegistration.setStartDate(startTime);
                        }
                        if (!StringUtils.isEmpty(endDate)){
                            endTime = format.parse(endDate);
                            parkingLocationRegistration.setEndDate(endTime);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    StringBuilder vins = new StringBuilder();
                    List vinList = (List) obj.get("vin");//数组
                    if (vinList!=null&&vinList.size()>0){
                        for (int i = 0; i < vinList.size(); i++) {
                            vins.append(vinList.get(i));
                            vins.append(",");
                        }
                    }
                    if (!StringUtils.isEmpty(vins)){
                        vins.deleteCharAt(vins.length()-1);
                        parkingLocationRegistration.setVin(vins.toString());
                    }
                    Object distanceFrom4s = obj.get("distanceFrom4s");
                    if (distanceFrom4s!=null){
                        parkingLocationRegistration.setDistanceFrom4s((String) distanceFrom4s);
                    }
                    Object tel = obj.get("tel");
                    if (tel!=null){
                        parkingLocationRegistration.setTel((String) tel);
                    }
                    Object notes = obj.get("notes");
                    if (notes!=null){
                        parkingLocationRegistration.setNotes((String) notes);
                    }
                    parkingLocationRegistration.setId(IdUtils.simpleUUID());
                    parkingLocationRegistrationMapper.insertParkingLocationRegistration(parkingLocationRegistration);

                    // 保存上传文件到数据库中
                    Object uploadFile = obj.get("uploadFile");
                    if(uploadFile!=null){
                        List<Fileupload> fileuploads= (List<Fileupload>) uploadFile;
                        String s = JSON.toJSONString(fileuploads);
                        fileuploads = JSON.parseArray(s, Fileupload.class);
                        System.out.println("parkingLocationRegistration上传文件的内容： "+fileuploads);
                        if (fileuploads!=null&&fileuploads.size()>0){
                            for (Fileupload fileupload : fileuploads) {
                                fileupload.setId(IdUtils.simpleUUID());
                                fileupload.setInstanceId(parkingLocationRegistration.getId());
                                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                                fileupload.setCreateName(SecurityUtils.getNickName());
                                fileupload.setCreateTime(new Date());
                                fileupload.setType("parkingLocationRegistration");
                                fileuploadService.insertFileupload(fileupload);
                            }
                        }
                    }

                }
            }

        }

        AnnualReviewy annualReviewy=new AnnualReviewy();
        annualReviewy.setId(instanceId);
        annualReviewy.setInstanceId(instanceId);
        annualReviewy.setTitle(title);
        annualReviewy.setType("parkingLocationRegistration");  // TODO 待确认，先暂时随便写一个
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setState("0");
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        // annualReviewy.setUsername(); // TODO 先不填
        return annualReviewyMapper.insertAnnualReviewy(annualReviewy);
    }


}
